#include "lrc_parser.h"
#include <algorithm>
#include <taglib/flacfile.h>
#include <taglib/id3v2tag.h>
#include <taglib/mp4file.h>
#include <taglib/mp4tag.h>
#include <taglib/mpegfile.h>
#include <taglib/unsynchronizedlyricsframe.h>
#include <taglib/vorbisfile.h>

 std::string LrcParser::getLyrics(const std::string &filePath) {
    // 获取文件扩展名并转为小写
    std::string ext = filePath.substr(filePath.find_last_of(".") + 1);
    std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);

    if (ext == "flac") {
        return getFlacLyrics(filePath);
    } else if (ext == "mp3") {
        return getMp3Lyrics(filePath);
    } else if (ext == "ogg") {
        return getOggLyrics(filePath);
    }
    return ""; // 不支持的格式
}

std::string LrcParser::getFlacLyrics(const std::string &filePath) {
    TagLib::FLAC::File file(filePath.c_str());
    if (!file.isValid())
        return "";

    TagLib::Ogg::XiphComment *vorbisComment = file.xiphComment();
    if (!vorbisComment)
        return "";

    const auto &fields = vorbisComment->fieldListMap();
    if (fields.contains("LYRICS")) {
        const TagLib::StringList &lyricsList = fields["LYRICS"];
        if (!lyricsList.isEmpty()) {
            return lyricsList.front().toCString(true);
        }
    }

    return "";
}

std::string LrcParser::getMp3Lyrics(const std::string &filePath) {
    TagLib::MPEG::File file(filePath.c_str());
    if (!file.isValid() || !file.ID3v2Tag())
        return "";

    TagLib::ID3v2::Tag *id3v2Tag = file.ID3v2Tag();
    TagLib::ID3v2::FrameList frameList = id3v2Tag->frameList("USLT");

    if (!frameList.isEmpty()) {
        TagLib::ID3v2::UnsynchronizedLyricsFrame *lyricsFrame =
            dynamic_cast<TagLib::ID3v2::UnsynchronizedLyricsFrame *>(frameList.front());

        if (lyricsFrame) {
            return lyricsFrame->text().toCString(true);
        }
    }

    return "";
}

std::string LrcParser::getOggLyrics(const std::string &filePath) {
    TagLib::Ogg::Vorbis::File file(filePath.c_str());
    if (!file.isValid())
        return "";

    TagLib::Ogg::XiphComment *vorbisComment = file.tag();
    if (!vorbisComment)
        return "";

    const auto &fields = vorbisComment->fieldListMap();
    if (fields.contains("LYRICS")) {
        const TagLib::StringList &lyricsList = fields["LYRICS"];
        if (!lyricsList.isEmpty()) {
            return lyricsList.front().toCString(true);
        }
    }

    return "";
}